package com.sikaryofficial.backend.manager.information;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sikaryofficial.backend.config.TenantFilterProperties;
import com.sikaryofficial.backend.constant.ArticleRedisKey;
import com.sikaryofficial.backend.domain.dto.req.information.ArticleBannerH5ListReq;
import com.sikaryofficial.backend.domain.dto.req.information.ArticleBannerListReq;
import com.sikaryofficial.backend.domain.dto.req.information.ArticleBannerReq;
import com.sikaryofficial.backend.domain.dto.resp.information.ArticleBannerDTO;
import com.sikaryofficial.backend.domain.entity.ArticleBanner;
import com.sikaryofficial.backend.domain.mapping.ArticleBannerMapping;
import com.sikaryofficial.backend.service.IArticleBannerService;
import com.sikaryofficial.common.core.constant.BrandEnum;
import com.sikaryofficial.common.core.exception.ServiceException;
import com.sikaryofficial.common.redis.service.RedisService;
import com.sikaryofficial.common.security.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author : qinjinyuan
 * @desc : 文章banner聚合类
 * @date : 2024/04/10 10:46
 */
@Component
@Slf4j
@SuppressWarnings(value = "unchecked")
public class ArticleBannerManager {
    private static final String BRAND_HISMK = BrandEnum.HISMK.getCode().toUpperCase(Locale.ROOT);
    @Autowired
    private IArticleBannerService articleBannerService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private TenantFilterProperties tenantFilterProperties;

    private String buildCacheKey(Integer sectionPosition) {
        String bandNo = SecurityUtils.getBrand();
        bandNo = CharSequenceUtil.isBlank(bandNo) ? BRAND_HISMK : bandNo;
        return MessageFormat.format(ArticleRedisKey.ARTICLE_BANNER_LIST_KEY, bandNo, sectionPosition);
    }

    /**
     * banner 列表
     *
     * @return
     */
    public List<ArticleBannerDTO> list(ArticleBannerH5ListReq req) {
        String cacheKey = buildCacheKey(req.getSectionPosition());
        List<ArticleBannerDTO> cacheValue = redisService.getCacheObject(cacheKey);
        if (Objects.isNull(cacheValue)) {
            LambdaQueryWrapper<ArticleBanner> lambdaQueryWrapper = new LambdaQueryWrapper<ArticleBanner>()
                    .select(ArticleBanner::getArticleBannerId, ArticleBanner::getClickLink, ArticleBanner::getCoverUrl,
                            ArticleBanner::getSort, ArticleBanner::getHasOutLink, ArticleBanner::getBannerName)
                    .eq(ArticleBanner::getDeletedVersion, 0)
                    .eq(ArticleBanner::getSectionPosition, req.getSectionPosition())
                    .eq(ArticleBanner::getVisible, 0)
                    .orderByDesc(ArticleBanner::getSort,ArticleBanner::getCreatedTime,ArticleBanner::getUpdatedTime);
            List<ArticleBanner> list = articleBannerService.list(lambdaQueryWrapper);
            cacheValue = ArticleBannerMapping.INSTANCE.coverToDTOList(list);
            if (CollUtil.isNotEmpty(cacheValue)) {
                cacheValue = cacheValue.stream().sorted(Comparator.comparingInt(ArticleBannerDTO::getSort)).collect(Collectors.toList());
                redisService.setCacheObject(cacheKey, cacheValue);
            }
        }
        return cacheValue;
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean saveOrUpdate(ArticleBannerReq req) {
        Integer tenantId = CharSequenceUtil.isNotBlank(req.getBrand()) ? tenantFilterProperties.getTenantByBrand(req.getBrand().toUpperCase()) : null;
        ArticleBanner articleBanner = ArticleBannerMapping.INSTANCE.coverReqToEntity(req);
        articleBanner.setTenantId(tenantId);
        if (Objects.nonNull(req.getArticleBannerId())) {
            articleBanner.setUpdatedBy(SecurityUtils.getUserId());
            articleBanner.setUpdatedTime(new Date());
            if (articleBannerService.count(new LambdaQueryWrapper<ArticleBanner>()
                    .eq(ArticleBanner::getArticleBannerId, req.getArticleBannerId())
                    .eq(ArticleBanner::getDeletedVersion, 0L)) == 0) {
                throw new ServiceException("the banner has deleted");
            }
        }else{
            articleBanner.setCreatedBy(SecurityUtils.getUserId());
            articleBanner.setCreatedName(SecurityUtils.getUsername());
        }
        // 清除缓存
        cleanCache();
        return articleBannerService.saveOrUpdate(articleBanner);
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean remove(String articleBannerIds) {
        List<Long> articleBannerIdList = Lists.newArrayList();
        Arrays.asList(articleBannerIds.split(",")).forEach(
                articleBannerId -> articleBannerIdList.add(Long.valueOf(articleBannerId))
        );
        // 清除缓存
        cleanCache();
        return articleBannerService.update(new LambdaUpdateWrapper<ArticleBanner>()
                .setSql("   deleted_version = article_banner_id  ")
                .set(ArticleBanner::getUpdatedBy, SecurityUtils.getUserId())
                .set(ArticleBanner::getUpdatedTime, new Date())
                .in(ArticleBanner::getArticleBannerId, articleBannerIdList)
                .eq(ArticleBanner::getDeletedVersion, 0L)
        );
    }

    public IPage<ArticleBannerDTO> listPage(ArticleBannerListReq req) {
        Page<ArticleBanner> customerPage = new Page<>(req.getPageNum(), req.getPageSize());
        log.info("brand:{}", req.getBrand());
        Integer tenantId = CharSequenceUtil.isNotBlank(req.getBrand()) ? tenantFilterProperties.getTenantByBrand(req.getBrand().toUpperCase()) : null;
        LambdaQueryWrapper<ArticleBanner> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(ArticleBanner::getArticleBannerId, ArticleBanner::getBannerName,
                        ArticleBanner::getVisible,ArticleBanner::getCreatedName,ArticleBanner::getCreatedTime,
                        ArticleBanner::getClickLink,ArticleBanner::getTenantId,
                        ArticleBanner::getVisible)
                .eq(Objects.nonNull(tenantId), ArticleBanner::getTenantId, tenantId)
                .eq(ArticleBanner::getDeletedVersion, 0L)
                .likeRight(CharSequenceUtil.isNotBlank(req.getBannerName()),ArticleBanner::getBannerName, req.getBannerName())
                .eq(Objects.nonNull(req.getVisible()),ArticleBanner::getVisible, req.getVisible())
                .eq(CharSequenceUtil.isNotBlank(req.getCountry()),ArticleBanner::getCountry, req.getCountry())
                .eq(CharSequenceUtil.isNotBlank(req.getArea()),ArticleBanner::getArea, req.getArea())
                .eq(CharSequenceUtil.isNotBlank(req.getCity()),ArticleBanner::getCity, req.getCity())
        ;
        if (Objects.nonNull(req.getStartTime()) || Objects.nonNull(req.getEndTime())) {
            queryWrapper.and(
                    i -> i.between(Objects.nonNull(req.getStartTime()) && Objects.nonNull(req.getEndTime()),
                            ArticleBanner::getCreatedTime, req.getStartTime(), req.getEndTime())
            );
        }
        queryWrapper.orderByDesc(ArticleBanner::getArticleBannerId).orderByAsc(ArticleBanner::getVisible);
        IPage<ArticleBanner> page = articleBannerService.page(customerPage, queryWrapper);
        List<ArticleBanner> articleList = page.getRecords();
        if (CollUtil.isEmpty(articleList)) {
            return new Page<>(req.getPageNum(), req.getPageSize(), 0);
        }
        IPage<ArticleBannerDTO> page1 = page.convert(ArticleBannerMapping.INSTANCE::coverToDTO);
        List<ArticleBannerDTO> articleDTOList = page1.getRecords();
        articleDTOList.forEach(item -> {
            if (Objects.isNull(item.getTenantId())) {
                item.setBrandNo(BRAND_HISMK);
            } else {
                item.setBrandNo(tenantFilterProperties.getBrandByTenantId(item.getTenantId()));
            }
        });
        return page1;
    }

    public ArticleBannerDTO detail(Long articleBannerId) {
        ArticleBanner articleBanner = articleBannerService.getOne(new LambdaQueryWrapper<ArticleBanner>()
                .eq(ArticleBanner::getArticleBannerId, articleBannerId)
                .eq(ArticleBanner::getDeletedVersion, 0L)
                .last(" limit 1 ")
        );
        if (Objects.isNull(articleBanner)) {
            throw new ServiceException("the banner has deleted");
        }
        ArticleBannerDTO articleBannerDTO = ArticleBannerMapping.INSTANCE.coverToDTO(articleBanner);
        if (Objects.isNull(articleBannerDTO.getTenantId())) {
            articleBannerDTO.setBrandNo(BRAND_HISMK);
        } else {
            articleBannerDTO.setBrandNo(tenantFilterProperties.getBrandByTenantId(articleBanner.getTenantId()));
        }
        return articleBannerDTO;
    }

    public boolean setVisible(Long articleBannerId, Integer visible) {
        boolean flag = articleBannerService.update(ArticleBanner.builder().visible(visible).updatedBy(SecurityUtils.getUserId())
                .updatedTime(new Date()).build(), new LambdaQueryWrapper<ArticleBanner>()
                .eq(ArticleBanner::getArticleBannerId, articleBannerId).eq(ArticleBanner::getDeletedVersion, 0L));
        cleanCache();
        return flag;
    }

    /**
     * 清除缓存
     */
    private void cleanCache() {
        // 清除缓存
        Collection<String> collKeys = redisService.keys(ArticleRedisKey.ARTICLE_BANNER_LIST_ITEM + "*");
        redisService.deleteObject(collKeys);
    }


}
